<template>
    <el-dialog draggable v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false"
        @closed="resetForm">

        <el-alert type="info" show-icon :closable="false" title="提示" description="如果添加的计划与已有计划时间范围重叠，系统将会自动修改原计划值。"
            style="margin-bottom: 15px;" />
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
            <!-- 计划类型选择 -->
            <el-form-item label="计划类型" prop="planType">
                <el-radio-group v-model="formData.planType">
                    <el-radio-button label="month">月度计划</el-radio-button>
                    <el-radio-button label="quarter">季度计划</el-radio-button>
                    <el-radio-button label="year">年度计划</el-radio-button>
                </el-radio-group>
            </el-form-item>

            <!-- 年份选择 -->
            <el-form-item label="年份" prop="year">
                <el-date-picker v-model="formData.year" type="year" placeholder="请选择年份" format="YYYY"
                    value-format="YYYY" style="width: 100%" />
            </el-form-item>

            <!-- 月份选择 (仅当选择月度计划时显示) -->
            <el-form-item v-if="formData.planType === 'month'" label="月份" prop="month">
                <el-select v-model="formData.month" placeholder="请选择月份" style="width: 100%">
                    <el-option v-for="month in monthOptions" :key="month.value" :label="month.label"
                        :value="month.value" />
                </el-select>
            </el-form-item>

            <!-- 季度选择 (仅当选择季度计划时显示) -->
            <el-form-item v-if="formData.planType === 'quarter'" label="季度" prop="quarter">
                <el-select v-model="formData.quarter" placeholder="请选择季度" style="width: 100%">
                    <el-option v-for="quarter in quarterOptions" :key="quarter.value" :label="quarter.label"
                        :value="quarter.value" />
                </el-select>
            </el-form-item>

            <!-- 资源类型选择 -->
            <el-form-item label="资源类型" prop="metricType">
                <el-radio-group v-model="formData.metricType">
                    <el-radio-button :label="planV2Store.PLAN_TYPES.WATER">用水量</el-radio-button>
                    <el-radio-button :label="planV2Store.PLAN_TYPES.ELECTRICITY">用电量</el-radio-button>
                    <el-radio-button :label="planV2Store.PLAN_TYPES.GAS">用气量</el-radio-button>
                </el-radio-group>
            </el-form-item>

            <!-- 计划值输入框 -->
            <el-form-item :label="resourceUnitLabel" prop="value">
                <el-input-number v-model="formData.value" :min="0" :precision="2" :step="0.1" style="width: 100%"
                    :placeholder="`请输入计划${resourceTypeText}`" />
            </el-form-item>
        </el-form>


        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { useCompanyStore } from '@/stores/company';
import { usePlanV2Store } from '@/stores/planV2';

// 定义emit
const emit = defineEmits(['refresh']);

// 获取store
const companyStore = useCompanyStore();
const planV2Store = usePlanV2Store();

// 对话框可见状态
const dialogVisible = ref(false);
const submitting = ref(false);
const formRef = ref(null);

// 月份选项
const monthOptions = Array.from({ length: 12 }, (_, i) => ({
    label: `${i + 1}月`,
    value: i + 1
}));

// 季度选项
const quarterOptions = Array.from({ length: 4 }, (_, i) => ({
    label: `第${i + 1}季度`,
    value: i + 1
}));

// 表单数据
const formData = reactive({
    planType: 'month',
    year: dayjs().format('YYYY'),
    month: null,
    quarter: null,
    metricType: planV2Store.PLAN_TYPES.WATER,
    value: null
});

// 资源类型文本
const resourceTypeText = computed(() => {
    switch (formData.metricType) {
        case planV2Store.PLAN_TYPES.WATER: return '用水量';
        case planV2Store.PLAN_TYPES.ELECTRICITY: return '用电量';
        case planV2Store.PLAN_TYPES.GAS: return '用气量';
        default: return '用水量';
    }
});

// 资源单位标签
const resourceUnitLabel = computed(() => {
    switch (formData.metricType) {
        case planV2Store.PLAN_TYPES.WATER: return '计划用水量';
        case planV2Store.PLAN_TYPES.ELECTRICITY: return '计划用电量';
        case planV2Store.PLAN_TYPES.GAS: return '计划用气量';
        default: return '计划用水量';
    }
});

// 表单验证规则
const formRules = {
    year: [{ required: true, message: '请选择年份', trigger: 'change' }],
    month: [{ required: true, message: '请选择月份', trigger: 'change' }],
    quarter: [{ required: true, message: '请选择季度', trigger: 'change' }],
    value: [{ required: true, message: '请输入计划值', trigger: 'blur' }]
};

// 动态标题
const dialogTitle = computed(() => {
    const periodText = {
        month: '月度',
        quarter: '季度',
        year: '年度'
    }[formData.planType];
    return `编辑${periodText}${resourceTypeText.value}计划`;
});

// 计算时间范围
const calculateTimeRange = () => {
    const year = Number(formData.year);

    if (formData.planType === 'month' && formData.month) {
        // 月度计划: 当月第一天到最后一天
        const month = formData.month - 1; // JavaScript月份从0开始
        const startDate = new Date(year, month, 1);
        const endDate = new Date(year, month + 1, 0); // 下个月的第0天就是当月最后一天
        return {
            start_time: startDate.getTime(),
            end_time: endDate.getTime()
        };
    } else if (formData.planType === 'quarter' && formData.quarter) {
        // 季度计划: 季度第一天到最后一天
        const startMonth = (formData.quarter - 1) * 3;
        const startDate = new Date(year, startMonth, 1);
        const endDate = new Date(year, startMonth + 3, 0);
        return {
            start_time: startDate.getTime(),
            end_time: endDate.getTime()
        };
    } else if (formData.planType === 'year') {
        // 年度计划: 当年第一天到最后一天
        const startDate = new Date(year, 0, 1);
        const endDate = new Date(year, 11, 31);
        return {
            start_time: startDate.getTime(),
            end_time: endDate.getTime()
        };
    }

    return null;
};

// 检查是否存在相同时间段的计划
const checkExistingPlan = (timeRange, metricType) => {
    if (!planV2Store.allPlansData || planV2Store.allPlansData.length === 0) {
        return null;
    }


    // 获取当前计划类型的周期长度
    const getPlanPeriodType = (startTime, endTime) => {
        const start = dayjs(startTime);
        const end = dayjs(endTime);
        const diffDays = end.diff(start, 'day');

        if (diffDays <= 31) return 'month';
        if (diffDays <= 100) return 'quarter';
        return 'year';
    };

    // 获取要添加的计划的周期类型
    const newPlanPeriodType = getPlanPeriodType(timeRange.start_time, timeRange.end_time);

    // 查找相同时间范围、类型和周期类型的计划
    const existingPlan = planV2Store.allPlansData.find(plan => {
        // 首先检查计划类型是否相同
        const isSameType = parseInt(plan.type) === parseInt(metricType);
        if (!isSameType) return false;

        // 获取已存在计划的周期类型
        const existingPlanPeriodType = getPlanPeriodType(plan.start_time, plan.end_time);

        // 如果周期类型不同，则不是重复计划
        // 例如，年度计划和季度计划即使时间有重叠也视为不同的计划
        if (existingPlanPeriodType !== newPlanPeriodType) return false;

        // 只对相同周期类型的计划进行时间重叠检测
        const planStartDate = dayjs(plan.start_time);
        const planEndDate = dayjs(plan.end_time);
        const requestStartDate = dayjs(timeRange.start_time);
        const requestEndDate = dayjs(timeRange.end_time);

        // 对于相同周期类型的计划，检查开始日期和结束日期是否相同
        // 使用dayjs的startOf('day')确保只比较日期部分
        const isSameStartDay = planStartDate.startOf('day').isSame(requestStartDate.startOf('day'));
        const isSameEndDay = planEndDate.startOf('day').isSame(requestEndDate.startOf('day'));
        // 只有当开始和结束日期都相同时，才认为是重复计划
        return isSameStartDay && isSameEndDay;
    });

    return existingPlan || null;
};

// 提交表单
// 修改后的提交表单函数
const submitForm = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
        if (!valid) return;

        submitting.value = true;

        try {
            // 获取公司ID
            const companyId = companyStore.currentCompany?.id;
            if (!companyId) {
                ElMessage.error('未选择公司');
                return;
            }

            // 计算时间范围
            const timeRange = calculateTimeRange();
            if (!timeRange) {
                ElMessage.error('计算时间范围出错');
                return;
            }

            // 检查输入的计划值是否为0
            if (formData.value === 0) {
                // 检查是否已存在相同时间范围和类型的计划
                const existingPlan = checkExistingPlan(timeRange, formData.metricType);

                if (existingPlan) {
                    // 存在计划，询问用户是否要删除
                    try {
                        // 格式化时间范围为用户友好的文本
                        const formatStartTime = dayjs(existingPlan.start_time).format('YYYY-MM-DD');
                        const formatEndTime = dayjs(existingPlan.end_time).format('YYYY-MM-DD');

                        await ElMessageBox.confirm(
                            `计划值为0将删除该计划。确定要删除时间范围(${formatStartTime}至${formatEndTime})的${resourceTypeText.value}计划吗？`,
                            '删除计划确认',
                            {
                                confirmButtonText: '删除',
                                cancelButtonText: '取消',
                                type: 'warning',
                            }
                        );

                        // 用户确认删除，调用删除API
                        const deleteData = {
                            id: existingPlan.id
                        };

                        await planV2Store.deletePlanV2(deleteData);

                        // 删除成功后重新获取数据以确保刷新
                        await planV2Store.fetchPlanData(companyId);

                        ElMessage.success('删除计划成功');
                        dialogVisible.value = false;
                        emit('refresh');
                    } catch (e) {
                        // 用户取消操作
                        if (e === 'cancel') {
                            ElMessage.info('已取消删除计划');
                        } else {

                            ElMessage.error('操作失败');
                        }
                    }
                } else {
                    // 不存在计划，提示用户
                    ElMessage.warning('无法添加计划值为0的计划');
                }
                submitting.value = false;
                return;
            }

            // 检查是否已存在相同时间范围和类型的计划（非零值计划的处理）
            const existingPlan = checkExistingPlan(timeRange, formData.metricType);
            if (existingPlan) {
                // 格式化时间范围为用户友好的文本
                const formatStartTime = dayjs(existingPlan.start_time).format('YYYY-MM-DD');
                const formatEndTime = dayjs(existingPlan.end_time).format('YYYY-MM-DD');

                try {
                    // 询问用户是否要更新现有计划
                    await ElMessageBox.confirm(
                        `已存在相同时间范围(${formatStartTime}至${formatEndTime})的${resourceTypeText.value}计划，原计划值为${existingPlan.value}，是否更新为${formData.value}？`,
                        '计划已存在',
                        {
                            confirmButtonText: '更新',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    );

                    // 用户确认更新
                    const requestData = {
                        id: existingPlan.id,
                        company_id: companyId,
                        type: formData.metricType,
                        value: String(formData.value), // API需要字符串类型的值
                        start_time: dayjs(existingPlan.start_time).valueOf(),
                        end_time: dayjs(existingPlan.end_time).valueOf()
                    };

                    await planV2Store.updatePlanV2(requestData);

                    // 更新成功后重新获取数据以确保刷新
                    await planV2Store.fetchPlanData(companyId);

                    ElMessage.success('更新计划成功');
                    dialogVisible.value = false;
                    emit('refresh');

                } catch (e) {
                    // 用户取消操作
                    if (e === 'cancel') {
                        ElMessage.info('已取消添加计划');
                    } else {

                        ElMessage.error('操作失败');
                    }
                }
                return;
            }

            // 不存在相同计划，执行添加操作
            const requestData = {
                company_id: companyId,
                type: formData.metricType,
                value: String(formData.value), // API需要字符串类型的值
                ...timeRange
            };

            await planV2Store.addPlanV2(requestData);

            // 添加成功后重新获取数据以确保刷新
            await planV2Store.fetchPlanData(companyId);

            ElMessage.success('添加计划成功');
            dialogVisible.value = false;
            emit('refresh');

        } catch (error) {

            ElMessage.error('操作失败');
        } finally {
            submitting.value = false;
        }
    });
};

// 打开对话框
// 打开对话框 - 增加year参数接收从父组件传来的年份
const openDialog = (type = 'month', metric = planV2Store.PLAN_TYPES.WATER, year = dayjs().format('YYYY')) => {
    formData.planType = type;
    formData.metricType = metric;
    // 设置年份为传入的年份
    formData.year = year;
    dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields();
    }
    formData.value = null;
    formData.month = null;
    formData.quarter = null;
};

// 暴露方法和属性给父组件
defineExpose({
    openDialog
});
</script>

<style lang="scss" scoped>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>